﻿using DeviceFaultPushService.MessagePushService.Models;
using DeviceFaultPushService.SystemService;
using System.IO.Ports;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace 设备报警推送服务
{
    public partial class 系统配置 : Form
    {
        public 系统配置()
        {
            InitializeComponent();
        }

        #region 显示行号
        private void dtLineHCurvePara_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            var grid = sender as DataGridView;
            var rowidx = (e.RowIndex).ToString();
            var centerFormat = new StringFormat()
            {
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };
            var headerBuunds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid!.RowHeadersWidth, e.RowBounds.Height);
            e.Graphics.DrawString(rowidx, new Font("宋体", 11), SystemBrushes.ControlText, headerBuunds, centerFormat);
        }
        #endregion

        private void 系统配置_Load(object sender, EventArgs e)
        {
            // 如果你想要同时设置所有列的标题都居中显示，你可以遍历所有列  
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                DataGridViewColumnHeaderCell header = column.HeaderCell;
                header.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }
            //加载信息通道
            cbPassageway.DataSource = Enum.GetNames(typeof(MessageChannelEnum));
            //加载全局设置
            int id = dataGridView1.Rows.Add();
            dataGridView1.Rows[id].Cells[0].Value = GetConfiguration.Configuration.CollectionInterval;
            dataGridView1.Rows[id].Cells[1].Value = GetConfiguration.Configuration.AlarmInterval;
            dataGridView1.Rows[id].Cells[2].Value = GetConfiguration.Configuration.EnableVoiceBroadcastingService;
            dataGridView1.Rows[id].Cells[3].Value = GetConfiguration.Configuration.EnablePushService;
            tbTemplate.Text = GetConfiguration.Configuration.Template;
            //加载联系人
            dataGridView2.Rows.Clear();
            if (GetConfiguration.Configuration.Contacts is not null)
            {
                for (int i = 0; i < GetConfiguration.Configuration.Contacts.Count; i++)
                {
                    int index = dataGridView2.Rows.Add();
                    dataGridView2.Rows[index].Cells[0].Value = GetConfiguration.Configuration.Contacts[i].PhoneNumber;
                    dataGridView2.Rows[index].Cells[1].Value = GetConfiguration.Configuration.Contacts[i].UserLevel.ToString();
                    dataGridView2.Rows[index].Cells[2].Value = GetConfiguration.Configuration.Contacts[i].EnableSms;
                    dataGridView2.Rows[index].Cells[3].Value = GetConfiguration.Configuration.Contacts[i].EnableDialing;
                }
            }
            cbPassageway.Text = GetConfiguration.Configuration.Passageway.ToString();

        }

        /// <summary>
        /// 判断是否未空
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        private string iSNull(object o)
        {
            if (o is null)
            {
                return " ";

            }
            return o.ToString()!;
        }

        private string isNullBool(object o)
        {
            if (o is not null)
            {
                return o.ToString()!;
            }
            return "false";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPreserve_Click(object sender, EventArgs e)
        {

            //退出验证服务
            Form form = new 验证服务();

            DialogResult dialogResult = form.ShowDialog();

            if (dialogResult != DialogResult.OK)
            {
                return;
            }

            GetConfiguration.Configuration.CollectionInterval = int.Parse(iSNull(dataGridView1.Rows[0].Cells[0].Value));
            GetConfiguration.Configuration.AlarmInterval = int.Parse(iSNull(dataGridView1.Rows[0].Cells[1].Value));
            GetConfiguration.Configuration.EnableVoiceBroadcastingService = bool.Parse(isNullBool(dataGridView1.Rows[0].Cells[2].Value));
            GetConfiguration.Configuration.EnablePushService = bool.Parse(isNullBool(dataGridView1.Rows[0].Cells[3].Value));
            GetConfiguration.Configuration.Template = tbTemplate.Text;
            GetConfiguration.Configuration.Contacts = new();

            for (int i = 0; i < dataGridView2.RowCount; i++)
            {
                if (iSNull(dataGridView2.Rows[i].Cells[0].Value).Length < 2)
                {
                    continue;
                }
                GetConfiguration.Configuration.Contacts.Add(new()
                {
                    PhoneNumber = iSNull(dataGridView2.Rows[i].Cells[0].Value),
                    UserLevel = (UserLevelEnum)Enum.Parse(typeof(UserLevelEnum), iSNull(dataGridView2.Rows[i].Cells[1].Value), true),
                    EnableSms = bool.Parse(isNullBool(dataGridView2.Rows[i].Cells[2].Value)),
                    EnableDialing = bool.Parse(isNullBool(dataGridView2.Rows[i].Cells[3].Value))
                });
            }

            MessageChannelEnum messageEnum = (MessageChannelEnum)Enum.Parse(typeof(MessageChannelEnum), cbPassageway.Text, true);

            if (messageEnum == MessageChannelEnum.SerialPort)
            {
                GetConfiguration.Configuration.Passageway = MessageChannelEnum.SerialPort;

                string jsonString = JsonSerializer.Serialize(new SerialCommunicationModel()
                {
                    SerialPort = cbSerialPort.Text,
                    BaudRate = int.Parse(tbSerialPort.Text)
                }, new JsonSerializerOptions()
                {
                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

                GetConfiguration.Configuration.PassagewayMessage = jsonString;
            }
            if (messageEnum == MessageChannelEnum.Socket)
            {
                GetConfiguration.Configuration.Passageway = MessageChannelEnum.Socket;

                string jsonString = JsonSerializer.Serialize(new SocketCommunicationModel()
                {
                    Ip = tbIp.Text,
                    Port = int.Parse(tbPort.Text)
                }, new JsonSerializerOptions()
                {
                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

                GetConfiguration.Configuration.PassagewayMessage = jsonString;
            }
            GetConfiguration.WriteConfiguration(GetConfiguration.Configuration);

            MessageBox.Show("保存成功");
        }

        private void cbPassageway_SelectedIndexChanged(object sender, EventArgs e)
        {
            MessageChannelEnum messageEnum = (MessageChannelEnum)Enum.Parse(typeof(MessageChannelEnum), cbPassageway.Text, true);

            if (messageEnum == MessageChannelEnum.Null)
            {
                panelSocket.Visible = false;
                panelSerialPort.Visible = false;
            }
            if (messageEnum == MessageChannelEnum.SerialPort)
            {
                cbSerialPort.Items.Clear();

                cbSerialPort.Items.AddRange(SerialPort.GetPortNames());

                if (cbSerialPort.Items.Count > 0)
                {
                    cbSerialPort.SelectedIndex = 0;
                }
                panelSerialPort.Visible = true;
                panelSocket.Visible = false;

                if (GetConfiguration.Configuration.PassagewayMessage is not null && GetConfiguration.Configuration.PassagewayMessage.Length > 2)
                {
                    //配置文件序列化
                    SerialCommunicationModel socketCommunication = JsonSerializer.Deserialize<SerialCommunicationModel>(GetConfiguration.Configuration.PassagewayMessage)!;
                    cbSerialPort.Text = socketCommunication.SerialPort;
                    tbSerialPort.Text = socketCommunication.BaudRate.ToString();
                }
            }

            if (messageEnum == MessageChannelEnum.Socket)
            {
                panelSerialPort.Visible = false;
                panelSocket.Visible = true;

                if (GetConfiguration.Configuration.PassagewayMessage is not null && GetConfiguration.Configuration.PassagewayMessage.Length > 2)
                {
                    //配置文件序列化
                    SocketCommunicationModel socketCommunication = JsonSerializer.Deserialize<SocketCommunicationModel>(GetConfiguration.Configuration.PassagewayMessage)!;

                    tbIp.Text = socketCommunication.Ip;
                    tbPort.Text = socketCommunication.Port.ToString();
                }

            }
        }
    }
}
